'use client';

import Link from 'next/link';
import { useState, useEffect, useRef } from 'react';
import { ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuth } from '@/hooks/use-auth';
import { navigationConfig } from '@/config/navigation';

interface NavItem {
  label: string;
  href: string;
  children?: NavItem[];
}

export function AdminNav() {
  const { user } = useAuth();
  const [openMenu, setOpenMenu] = useState<string | null>(null);
  const menuRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
  const buttonRefs = useRef<{ [key: string]: HTMLButtonElement | null }>({});

  const items = user ? navigationConfig[user.role] : [];

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (openMenu) {
        const menuElement = menuRefs.current[openMenu];
        const buttonElement = buttonRefs.current[openMenu];
        
        if (menuElement && buttonElement && 
            !menuElement.contains(event.target as Node) && 
            !buttonElement.contains(event.target as Node)) {
          setOpenMenu(null);
        }
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [openMenu]);

  const toggleMenu = (href: string) => {
    if (openMenu === href) {
      setOpenMenu(null);
    } else {
      setOpenMenu(href);
    }
  };

  const setButtonRef = (href: string) => (el: HTMLButtonElement | null) => {
    buttonRefs.current[href] = el;
  };

  const setMenuRef = (href: string) => (el: HTMLDivElement | null) => {
    menuRefs.current[href] = el;
  };

  if (!user) {
    return null;
  }

  return (
    <nav className="hidden md:flex ml-8">
      <ul className="flex gap-2">
        {items.map((item) => (
          <li key={item.href} className="relative">
            {item.children ? (
              <>
                <button
                  ref={setButtonRef(item.href)}
                  onClick={() => toggleMenu(item.href)}
                  className={cn(
                    "group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none",
                    openMenu === item.href && "bg-accent text-accent-foreground"
                  )}
                >
                  {item.label}
                  <ChevronDown
                    className={cn(
                      "ml-1 h-3 w-3 transition-transform duration-200",
                      openMenu === item.href ? "rotate-180" : ""
                    )}
                  />
                </button>
                <div 
                  ref={setMenuRef(item.href)}
                  className={cn(
                    "absolute z-10 mt-1 w-56 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none transition-all duration-200 ease-in-out transform origin-top",
                    openMenu === item.href 
                      ? "opacity-100 scale-100" 
                      : "opacity-0 scale-95 invisible"
                  )}
                >
                  <ul className="py-1">
                    {item.children.map((child, index) => (
                      <li 
                        key={child.href}
                        className="transition-all duration-200 ease-in-out"
                        style={{ 
                          transitionDelay: `${index * 50}ms`,
                          opacity: openMenu === item.href ? 1 : 0,
                          transform: openMenu === item.href 
                            ? 'translateX(0)' 
                            : 'translateX(-10px)'
                        }}
                      >
                        <Link
                          href={child.href}
                          onClick={() => setOpenMenu(null)}
                          className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors duration-150"
                        >
                          {child.label}
                        </Link>
                      </li>
                    ))}
                  </ul>
                </div>
              </>
            ) : (
              <Link
                href={item.href}
                className="group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none"
              >
                {item.label}
              </Link>
            )}
          </li>
        ))}
      </ul>
    </nav>
  );
} 